<?
require_once($r."_config/db.php");
require_once($r."_engine/c_sql_table.php");

$g_st_news = new CSqlTable("news", "id");
$g_st_news->field_types["dt"] = "dt";

class CNews
{
	var $id, $data;
	
	function InitNew()
	{
		// Initialize
		$this->data["dt"]		= gmt_time();
		$this->data["title"]	= "Untitled";
		$this->data["text"]		= "";
	}

	function Insert($values)
	{
		global $g_st_news;
		return $g_st_news->Insert($values);
	}

	function GetDT()
	{
		$dt = $this->data["dt"];

		global $account;
		if (isset($account)) $dt = $account->TimeToUserTZ($dt);

		return @date('M j, Y \a\t G:i', $dt);
	}

	function LoadById($id)
	{
		return $this->LoadByQuery(
			"SELECT * FROM news WHERE id='$id';"
		);
	}
	function LoadByQuery($query)
	{
		global $g_st_news;
		$row = $g_st_news->SelectRow($query);
		if (!$row) return false;
		$this->LoadFromArray($row);
		return true;
	}
	
	function LoadFromArray($row)
	{
		foreach($row as $f => $v)
		{
			if (is_int($f)) continue;
			
			if ($f == "id")
				$this->id = $v;
			else
				$this->data[$f] = $v;
		}
	}
	
	function Update($values)
	{
		global $g_st_news;
		$this->LoadFromArray($values);
		return $g_st_news->Update($values, $this->id);
	}
}

function GetNews($type="")
{
	$q = "SELECT * FROM news ORDER BY id DESC;";

	if ($type == "FP")
		$q = "SELECT * FROM news WHERE option_is_archived <> 1 AND option_show_on_fp = 1 ORDER BY id DESC LIMIT 0, 3;";

	if ($type == "News")
		$q = "SELECT * FROM news WHERE option_is_archived <> 1 ORDER BY id DESC;";
		
	if ($type == "Archive")
		$q = "SELECT * FROM news WHERE option_is_archived = 1 ORDER BY id DESC;";

	global $g_st_news;
	$rows = $g_st_news->SelectRows($q);
	
	$results = array();
	
	foreach ($rows as $k => $v)
	{
		$n = new CNews();
		$n->LoadFromArray($v);
		$results[] = $n;
	}
	
	return $results;
}

function GetLatestNews()
{
	global $g_st_news;
	$row = $g_st_news->SelectRow("SELECT * FROM news ORDER BY id DESC;");
	if (!$row) return false;

	$n = new CNews();
	$n->LoadFromArray($row);	
	
	return $n;
}
?>